<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="nav-bar">
			<view class="nav-left">
				<uni-icons type="back" size="24" @click="goBack" />
			</view>
			<view class="nav-title">发布代取</view>
			<view class="nav-right">
				<uni-icons type="paperplane" size="24" @click="onSubmit" />
			</view>
		</view>
		<!-- 主内容区 -->
		<scroll-view class="content" scroll-y>
			<!-- 快递位置选择 -->
			<view class="form-item">
				<view class="form-label">快递位置</view>
				<view class="location-selector" @click="toggleLocationSelect">
					<view class="selected-location">{{ selectedLocation || '请选择快递柜位置' }}</view>
					<uni-icons :type="isLocationSelectOpen ? 'top' : 'bottom'" size="16" />
				</view>
				<!-- 位置选择下拉框 -->
				<view v-if="isLocationSelectOpen" class="location-dropdown">
					<view v-for="(location, index) in locations" :key="index" class="location-option"
						@click="selectLocation(location)">
						{{ location }}
					</view>
				</view>
			</view>
			<!-- 取件码 -->
			<view class="form-item">
				<view class="form-label">取件码</view>
				<view class="tracking-input">
					<input type="text" v-model="formData.expressNo" placeholder="请输入取件码" class="input" maxlength="8" />
				</view>
			</view>

			<view class="form-item">
				<view class="label">期望收货时间</view>
				<view class="input-wrapper">
					<uni-datetime-picker v-model="formData.expectTime" type="datetime" :clear-icon="false"
						class="datetime-picker" />
				</view>
			</view>
			<!-- 寄件价格 -->
			<view class="form-item">
				<view class="form-label">寄件价格</view>
				<view class="price-input">
					<text class="currency">¥</text>
					<input type="digit" v-model="formData.fee" placeholder="请输入寄件价格" class="input" />
				</view>
			</view>
			<!-- 收件人信息 -->
			<view class="form-section">
				<view class="form-item">
					<view class="form-label">寄送地址</view>
					<textarea v-model="formData.senderAddress" placeholder="请输入寄件人详细地址" class="textarea" />
				</view>
			</view>
		</scroll-view>
		<!-- 底部按钮 -->
		<view class="bottom-button">
			<button class="submit-btn" :disabled="!isFormValid" @click="submitForm">
				确认发布
			</button>
		</view>
		<!-- 背景蒙层 -->
		<view v-if="isLocationSelectOpen" class="mask" @click="toggleLocationSelect" />
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed } from 'vue';
	import { getUserInfo } from '../../api/user';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { publishOrder } from '../../api/order';

	// 模拟位置数据
	const locations = [
		'1号快递柜 - A区',
		'2号快递柜 - B区',
		'3号快递柜 - C区',
		'4号快递柜 - D区'
	];

	// 用户数据
	const userData = ref(null);

	// 表单数据接口
	interface FormData {
		expressNo : string;
		expectTime : string; // 时间字符串，格式为 "yyyy-MM-dd HH:mm:ss"
		fee : number; // 费用，数值型
		senderAddress : string; // 输入的寄件人地址
		deliverAddress : string; // 快递位置 + 学校信息
	}

	// 定义表单数据
	const formData = ref<FormData>({
		expressNo: '',
		expectTime: '',
		fee: null, // 初始化为 null 或者 0
		senderAddress: '',
		deliverAddress: '' // 最终拼接后地址
	});

	// 当前选中的快递位置
	const selectedLocation = ref('');

	// 是否打开位置选择
	const isLocationSelectOpen = ref(false);

	// 位置选择下拉框的开关
	const toggleLocationSelect = () => {
		isLocationSelectOpen.value = !isLocationSelectOpen.value;
	};

	// 选择位置
	const selectLocation = (location : string) => {
		selectedLocation.value = location;
		isLocationSelectOpen.value = false;
		updateDeliverAddress();
	};

	// 更新配送地址（拼接快递位置 + 用户学校）
	const updateDeliverAddress = () => {
		if (selectedLocation.value && userData.value?.college) {
			formData.value.deliverAddress = `${selectedLocation.value} - ${userData.value.college}`;
		} else {
			formData.value.deliverAddress = '';
		}
	};

	// 校验表单是否有效
	const isFormValid = computed(() => {
		return (
			formData.value.expressNo &&
			formData.value.fee !== null &&
			formData.value.senderAddress &&
			formData.value.deliverAddress
		);
	});

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};


	function formatDateToISO(dateString : string) : string {
		if (!dateString) return ''; // 确保字段存在，避免报错
		return dateString.replace(" ", "T");
	}
	// 提交表单
	const submitForm = async () => {
		if (!isFormValid.value) return;
		uni.showLoading({
			title: '提交中'
		});
		formData.value.expectTime = formatDateToISO(formData.value.expectTime);


		// 调用发布订单 API
		const response = await publishOrder(formData.value);
		console.log(response)
		if (response.code === 200) {
			uni.showToast({
				title: '发布成功',
			});

			// 返回上一页
			uni.navigateBack({
				delta: 1,
			});
		};
		}

		// 提交操作

		// 获取用户数据
		const fetchUserData = async () => {
			try {
				const response = await getUserInfo();
				userData.value = response.data;
				updateDeliverAddress(); // 用户数据获取后更新配送地址
			} catch (error) {
				console.error('请求用户数据时出错:', error);
				userData.value = null;
			}
		};

		// 页面加载时获取用户数据
		onLoad(async () => {
			fetchUserData();
		});
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #f5f5f5;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		height: 88rpx;
		background-color: #ffffff;
		padding: 0 30rpx;
		flex-shrink: 0;
	}

	.nav-left {
		width: 88rpx;
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 16px;
		font-weight: 500;
	}

	.nav-right {
		width: 88rpx;
		display: flex;
		justify-content: flex-end;
	}

	.content {
		flex: 1;
		overflow: auto;
		padding: 20rpx 5rpx;
	}

	.form-item {
		background-color: #ffffff;
		border-radius: 8px;
		padding: 30rpx;
		margin-bottom: 20rpx;
		position: relative;
	}

	.form-label {
		font-size: 14px;
		color: #333333;
		margin-bottom: 20rpx;
	}

	.location-selector {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 88rpx;
		padding: 0 20rpx;
		background-color: #f8f8f8;
		border-radius: 4px;
	}

	.selected-location {
		font-size: 14px;
		color: #333333;
	}

	.location-dropdown {
		position: absolute;
		top: 100%;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-radius: 8px;
		margin-top: 10rpx;
		z-index: 100;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	}

	.location-option {
		padding: 30rpx;
		font-size: 14px;
		border-bottom: 1px solid #f5f5f5;
	}

	.location-option:last-child {
		border-bottom: none;
	}

	.tracking-input,
	.price-input {
		display: flex;
		align-items: center;
		background-color: #f8f8f8;
		border-radius: 4px;
		padding: 0 20rpx;
	}

	.currency {
		font-size: 16px;
		color: #333333;
		margin-right: 10rpx;
	}

	.input {
		flex: 1;
		height: 88rpx;
		font-size: 14px;
	}

	.textarea {
		width: 100%;
		height: 160rpx;
		background-color: #f8f8f8;
		border-radius: 4px;
		padding: 20rpx;
		font-size: 14px;
	}

	.form-section {
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 16px;
		font-weight: 500;
		margin-bottom: 20rpx;
		padding-left: 30rpx;
	}

	.bottom-button {
		padding: 30rpx;
		background-color: #ffffff;
		flex-shrink: 0;
	}

	.submit-btn {
		background-color: #007aff;
		color: #ffffff;
		font-size: 16px;
		border-radius: 8px;
	}

	.submit-btn[disabled] {
		background-color: #cccccc;
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		z-index: 99;
	}
</style>